package com.kma.summer2012.client.view.requests;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiTemplate;
import com.google.gwt.user.client.ui.*;
import com.kma.summer2012.client.constants.ConstantsHolder;
import com.kma.summer2012.client.styles.style2.Recources;
import com.kma.summer2012.shared.model.UIComment;
import com.kma.summer2012.shared.model.UICrumbsDateAndTime;
import com.kma.summer2012.shared.model.UICrumbsRequest;
import com.kma.summer2012.shared.model.UICrumbsWorkItem;

import java.util.ArrayList;
import java.util.Date;

public class EditRequestForOperator extends Request {
    @UiTemplate("Request.ui.xml")
    interface EditRequestUiBinder extends UiBinder<HTMLPanel, Request> {
    }

    private static EditRequestUiBinder editRequestUibinder = GWT.create(EditRequestUiBinder.class);

    public EditRequestForOperator() {

        super(editRequestUibinder);
        this.title.setText(constants.editRequest());
        this.id.setVisible(true);

        //this.comments.setEnabled(false);
        this.labelComments.setText("");
        this.comments.setVisible(false);
        this.saveButton.setVisible(false);
        this.backButton.setVisible(false);
        this.closeButton.setVisible(false);
        this.editButtonManager.setVisible(false);
        this.editButtonOperator.setVisible(true);
        this.deleteCloseButton.setVisible(false);
        this.sendForProcessingButton.setEnabled(true);
        this.assignButton.setVisible(false);
        this.catalog.setVisible(true);
        this.datePicker.addValueChangeHandler(new ValueChangeHandler<Date>() {
            public void onValueChange(ValueChangeEvent<Date> event) {
                Date date = event.getValue();
                String dateString = DateTimeFormat.getFormat(ConstantsHolder.getConstants().DATE_FORMAT_SHORT()).format(date);
                text.setText(dateString);
            }
        });
        setInnerStyle();
    }

    @Override
    public void setParametres(UICrumbsRequest request) {

        //nesessary data
        id.setText("" + request.getId());
        datelbl.setText(request.getDateOfCreation().toString());
        state.setText(request.getState());
        if (request.getState().equals(constants.rejectedState())) {
            sendForProcessingButton.setEnabled(false);
            getLastComment(request);
        }
        /* if (request.getState().equals(constants.rejectedState())) {
          this.comments.setEnabled(true);
          this.closeButton.setVisible(false);
      }  */
        clAddress.setText(request.getUicrumbsClient().getAdress());
        clMail.setText(request.getUicrumbsClient().getMail());
        clName.setText(request.getUicrumbsClient().getName());

        if (request.getUicrumbsWorkItems().size() > 0) {
            for (UICrumbsWorkItem key : request.getUicrumbsWorkItems().keySet()) {
                ArrayList<String> tmp = new ArrayList<String>();
                amountsOfWorkValues.put(key.getId(), (int) request.getUicrumbsWorkItems().get(key));
                tmp.add(key.getWorkName());
                tmp.add("" + key);
                Integer k = key.getId();
                workList.put(k, key);
                TextBox txt = new TextBox();
                txt.setValue("" + amountsOfWorkValues.get(key));
                amountOfWorkInTxtBox.put(k, txt);
                this.totalSumOfWork = request.getUicrumbsWorkItems().get(key) * key.getRuntime();
                //workList.put(request.getUicrumbsWorkItems().get(key).getId(), tmp);
            }
            updateWorkField();
        }
        if (request.getRequestInfo() != null)
            requestInfo.setText(request.getRequestInfo());
        else
            requestInfo.setText("");

        //if (request.getActualTimeOfWork() != null)
        timeRequired.setText("" + totalSumOfWork);
        /*else
            timeRequired.setText("");*/
        if (!(flexTable.getRowCount() > 0)) {
            flexTable.setVisible(false);
        }

        if (request.getUicrumbsDateAndTimes().size() > 0) {
            int index = 0;
            int id = 1;
            for (UICrumbsDateAndTime datatime : request.getUicrumbsDateAndTimes()) {
                if (index == 0) {
                    for (int i = 9; i < 19; i++) {

                        Date timestart = datatime.getDateBegin();
                        Date timeend = datatime.getDateEnd();

                        String st = DateTimeFormat.getFormat(ConstantsHolder.getConstants().DATE_FORMAT_FULL()).format(timestart);
                        String end = DateTimeFormat.getFormat(ConstantsHolder.getConstants().DATE_FORMAT_FULL()).format(timeend);
                        int s = DateTimeFormat.getFormat(ConstantsHolder.getConstants().DATE_FORMAT_FULL()).parse(st).getHours();
                        int e = DateTimeFormat.getFormat(ConstantsHolder.getConstants().DATE_FORMAT_FULL()).parse(end).getHours();
                        if (i == s) {

                            startTimeList.setSelectedIndex(id);
                            start_time = startTimeList.getItemText(id);
                        } else if (i == e) {

                            endTimeList.setSelectedIndex(id);
                            end_time = endTimeList.getItemText(id);
                        }
                        id++;

                    }
                    String dateString = DateTimeFormat.getFormat(ConstantsHolder.getConstants().DATE_FORMAT_SHORT()).format(datatime.getDateBegin());
                    text.setText(dateString);
                } else break;

                try {
                    this.timeAssigned.setText(DateTimeFormat.getFormat(ConstantsHolder.getConstants().DATE_FORMAT_FULL()).format(datatime.getAssignedTimeBegin()).concat(" - " + DateTimeFormat.getFormat(ConstantsHolder.getConstants().DATE_FORMAT_FULL()).format(datatime.getAssignedTimeEnd())));
                    this.labelTimeAssigned.setText(constants.assign());

                } catch (NullPointerException e) {
                    this.labelTimeAssigned.setText(constants.assignedTime());
                    timeAssigned.setText("No assigned time");
                }

            }

        }
        if (request.getState().equals(constants.newState())) {
            this.deleteCloseButton.setVisible(true);
        }
    }

    private void getLastComment(UICrumbsRequest request) {
        int size = request.getUicrumbsComments().size();
        try {
            if (size > 0) {

                comment_content = new Grid(1, 3);
                comment_content.setCellSpacing(6);
                int index = 0;
                int id = 0;
                UIComment com = new UIComment();
                for (UIComment comment : request.getUicrumbsComments()) {
                    if (comment.getId() > id) {
                        com = comment;
                        id = comment.getId();
                    }
                    index++;/*
                    if (index == (request.getUicrumbsComments().size() - 1)) {
                        if (comment.getComment() != null && comment.getComment() != "") {
                            comment_content.setWidget(0, 0, new Label(comment.getCommenter().getSurnmNmSecondnm()));
                            comment_content.setWidget(0, 1, new Label(comment.getCommentDate()));
                            comment_content.setWidget(0, 2, new Label(comment.getComment()));
                        }
                    } else index++;*/
                }
                comment_content.setWidget(0, 0, new Label(com.getCommenter().getSurnmNmSecondnm()));
                comment_content.setWidget(0, 1, new Label(com.getCommentDate()));
                comment_content.setWidget(0, 2, new Label(com.getComment()));
                commentField = new DisclosurePanel("See request's comment history");
                commentField.setAnimationEnabled(true);
                commentField.setContent(comment_content);
                cField.add(commentField);
            }
            ;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public Widget asWidget() {
        return this;
    }

    private void setInnerStyle() {
        //Input field that could be edited
        clAddress.addStyleName(Recources.INSTANCE.styles().TextAreaWritable());
        clMail.addStyleName(Recources.INSTANCE.styles().TextAreaWritable());
        clName.addStyleName(Recources.INSTANCE.styles().TextAreaWritable());
        requestInfo.addStyleName(Recources.INSTANCE.styles().TextAreaWritable());
    }

}
